import pandas as pd
from sklearn.metrics import precision_score, accuracy_score, roc_auc_score, recall_score, f1_score,classification_report, roc_curve
from utils.log import Logger
import joblib
from matplotlib import pyplot as plt
import matplotlib.ticker as mick
plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['font.size'] = 15
import os
os.environ['LOKY_MAX_CPU_COUNT'] = '4'

logger_obj = Logger("../", log_name="predict")  # 实例化日志类对象
logger = logger_obj.get_logger()    # 调用日志方法


def init():
    df = pd.read_csv("../data/test2.csv", encoding="UTF-8")
    return df


def model_predict(df):
    logger.info("开始进行模型预测")

    # 1.加载模型和transform
    model = joblib.load("../model/model_LGBM.pkl")
    transformer = joblib.load("../model/transformer.pkl")

    # 1 删除某个特征列
    df1 = df.drop(["Over18", "StandardHours", "EmployeeNumber"], axis=1)

    # 2.热编码
    df1 = pd.get_dummies(df1)
    print(df1.head())

    # # 3、获取到特征值、目标值
    y = df1["Attrition"]

    x = df1.drop(["Attrition"], axis=1)
    print(y)
    print(x.columns)
    print(x.head())

    # 4.4.5 特征预处理(标准化)
    x_test = transformer.transform(x)

    # 4.5. 使用测试集进行模型预测
    y_pred_proba = model.predict_proba(x_test)[:, 1]        # 获取预测的第一列
    y_pre = (y_pred_proba >= 0.2).astype(int)               # 获得预测的类别

    # 4.6 模型评估
    print(f"模型的准确率为：{accuracy_score(y, y_pre)}")
    print(f"ROC面积：{roc_auc_score(y, y_pred_proba)}")
    print(f"模型的精确率为：{precision_score(y, y_pre)}")

    print(f"模型的召回率为：{recall_score(y, y_pre)}")
    print(f"模型的f1指标为：{f1_score(y, y_pre)}")

    print("\n分类报告:")
    print(classification_report(y, y_pre, target_names=['留下', '离职']))

    # 6. 绘制 ROC 曲线（可选）
    fpr, tpr, _ = roc_curve(y, y_pred_proba)
    plt.figure()
    plt.plot(fpr, tpr, label=f'ROC Curve (AUC = {roc_auc_score(y, y_pred_proba):.4f})')
    plt.plot([0, 1], [0, 1], 'k--')
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('ROC Curve')
    plt.legend()
    plt.show()

    logger.info("完成模型预测和评估")
    return y_pre


def show_result(y_pre, init_df):
    # # 创建画布
    # fig = plt.figure(figsize=(40, 20), dpi=150)
    # ax = fig.add_subplot()
    #
    # # 绘制预测和真实的曲线
    # ax.plot(init_df["Gender"], y_pre, label="预测结果")  # 预测
    # ax.plot(init_df["Gender"], init_df["Attrition"], label="真实结果")  # 真实
    #
    # # x轴刻度尺美化
    # # 横坐标时间若不处理太过密集，这里调大时间展示的间隔
    # ax.xaxis.set_major_locator(mick.MultipleLocator(50))
    # # 时间展示时旋转45度
    # plt.xticks(rotation=45)
    #
    # # 其他属性设置
    # plt.title("预测结果展示")
    # plt.legend()
    #
    # # plt.savefig("../model/pic1.png")
    # plt.show()
    pass


if __name__ == '__main__':
    df = init()
    y_pre = model_predict(df)
    # show_result(y_pre, df)
